import ci from 'miniprogram-ci';
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
import debug from 'debug';

const log = debug('miniprogram-ci:service');
log.enabled = true;

export interface UploadOptions {
  projectPath: string;
  privateKeyPath: string;
  appid: string;
  type: string;
  version: string;
  desc: string;
  settings: any;
  robot: number;
  threads: number;
}

export interface PreviewOptions {
  projectPath: string;
  privateKeyPath: string;
  appid: string;
  type: string;
  version: string;
  desc: string;
}

export interface BuildOptions {
  projectPath: string;
}

export class MiniprogramCIService {
  /**
   * 上传小程序代码
   */
  async upload(options: UploadOptions, panel?: vscode.WebviewPanel): Promise<any> {
    log('开始上传小程序代码...');
    try {
      const { projectPath, privateKeyPath, appid, type, version, desc, settings, robot, threads } = options;

      log(`上传参数: appid=${appid}, version=${version}, desc=${desc}, robot=${robot}, threads=${threads}`);
      log(`项目路径: ${projectPath}`);
      log(`私钥路径: ${privateKeyPath}`);

      // 创建项目实例
      log('正在创建小程序项目实例...');
      const project = new ci.Project({
        appid,
        type: type as any,
        projectPath,
        privateKeyPath,
        ignores: ['node_modules/**/*'],
      });
      log('小程序项目实例创建成功');

      // 执行上传
      log('开始执行上传操作...');
      const uploadResult = await ci.upload({
        project,
        version,
        desc,
        // setting: settings,
        robot,
        threads,
        onProgressUpdate: (progress) => {
          log(`上传进度: %O`, progress);
          if (panel) {
            panel.webview.postMessage({
              command: 'uploadProgress',
              data: progress
            });
          }
        },
      });

      log('小程序代码上传成功');
      log(`上传结果: ${JSON.stringify(uploadResult)}`);
      return { success: true, result: uploadResult };
    } catch (error: any) {
      log(`上传失败: ${error.message}`);
      log(`错误堆栈: ${error.stack}`);
      return { success: false, error: error.message };
    }
  }

  /**
   * 预览小程序
   */
  async preview(options: PreviewOptions, panel?: vscode.WebviewPanel): Promise<any> {
    log('开始生成小程序预览...');
    try {
      const { projectPath, privateKeyPath, appid, type, version, desc } = options;

      log(`预览参数: appid=${appid}, version=${version}, desc=${desc}`);
      log(`项目路径: ${projectPath}`);
      log(`私钥路径: ${privateKeyPath}`);

      // 创建项目实例
      log('正在创建小程序项目实例...');
      const project = new ci.Project({
        appid,
        type: type as any,
        projectPath,
        privateKeyPath,
        ignores: ['node_modules/**/*'],
      });
      log('小程序项目实例创建成功');

      // 生成二维码文件路径
      const qrcodePath = path.join(os.tmpdir(), `miniprogram-preview-${Date.now()}.jpg`);
      log(`二维码临时文件路径: ${qrcodePath}`);

      // 执行预览
      log('开始执行预览操作...');
      const previewResult = await ci.preview({
        project,
        version,
        desc,
        setting: {
          // es7: true,
          // minifyJS: true,
          // minifyWXML: true,
          // minifyWXSS: true,
          // minify: true,
          // autoPrefixWXSS: true,
        },
        bigPackageSizeSupport: true,
        qrcodeFormat: 'image',
        qrcodeOutputDest: qrcodePath,
        onProgressUpdate: (progress) => {
          log(`预览进度: %O`, progress);
          if (panel) {
            panel.webview.postMessage({
              command: 'previewProgress',
              data: progress
            });
          }
        },
      });

      log('小程序预览生成成功');
      log(`预览结果: %O`, previewResult);

      // 读取二维码文件并转换为base64
      log('正在读取二维码文件...');
      const qrcodeBase64 = fs.readFileSync(qrcodePath, 'base64');
      log('二维码文件读取成功，正在转换为base64格式');
      
      // 清理临时文件
      try {
        fs.unlinkSync(qrcodePath);
        log('临时二维码文件已删除');
      } catch (e) {
        // 忽略清理错误
      }

      return {
        success: true,
        result: {
          ...previewResult,
          qrcode: `data:image/jpeg;base64,${qrcodeBase64}`
        }
      };
    } catch (error: any) {
      log(`预览失败: ${error.message}`);
      log(`错误堆栈: ${error.stack}`);
      return { success: false, error: error.message };
    }
  }

  /**
   * 执行npm构建
   */
  async npmBuild(options: BuildOptions, panel?: vscode.WebviewPanel): Promise<any> {
    try {
      const { projectPath } = options;

      // 模拟npm构建过程
      const steps = [
        '正在安装依赖...',
        '正在构建 npm 包...',
        '正在复制文件...',
        '构建完成'
      ];

      for (let i = 0; i < steps.length; i++) {
        await new Promise(resolve => setTimeout(resolve, 1000));
        if (panel) {
          panel.webview.postMessage({
            command: 'buildProgress',
            data: {
              progress: ((i + 1) / steps.length) * 100,
              step: steps[i]
            }
          });
        }
      }

      return { success: true };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  }
}

// 创建单例实例
export const miniprogramCIService = new MiniprogramCIService();